package com.zhonghe.active4j.filesys.controller;


import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.zhonghe.active4j.common.controller.BaseController;
import com.zhonghe.active4j.core.annotation.Log;
import com.zhonghe.active4j.core.model.AjaxJson;
import com.zhonghe.active4j.core.model.LogType;
import com.zhonghe.active4j.core.model.PageInfo;
import com.zhonghe.active4j.core.query.QueryUtils;
import com.zhonghe.active4j.core.util.MyBeanUtils;
import com.zhonghe.active4j.core.util.ResponseUtil;
import com.zhonghe.active4j.core.util.ShiroUtils;
import com.zhonghe.active4j.filesys.entity.SysConfigEntity;
import com.zhonghe.active4j.filesys.service.SysConfigService;
import com.zhonghe.active4j.filesys.wrapper.SysConfigWrapper;

import lombok.extern.slf4j.Slf4j;


/**
 * 系统定义
 * @author gyj
 *
 */
@Controller
@RequestMapping("/filesys/sysconfig")
@Slf4j
public class FileSysController extends BaseController {

	@Autowired
	private SysConfigService sysConfigService;
	
	
	/**
	 * 跳转到列表页面
	 * @param model
	 * @return
	 */
	@RequestMapping("/list")
	public String list(Model model) {
		return "filesys/sysconfig/sysconfig_list.html";
	}
	
	/**
	 *  获取表格数据 树形结构
	 * @param sysUserEntity
	 * @param request
	 * @return
	 */
	@RequestMapping("/datagrid")
	@ResponseBody
	public void datagrid(SysConfigEntity sysConfigEntity, PageInfo<SysConfigEntity> page, HttpServletRequest request, HttpServletResponse response) {
		//拼接查询条件
		QueryWrapper<SysConfigEntity> queryWrapper = QueryUtils.installQueryWrapper(sysConfigEntity, request.getParameterMap());
		
		//执行查询
		IPage<SysConfigEntity> lstResult = sysConfigService.page(page.getPageEntity(), queryWrapper);

		//结果处理,直接写到客户端
		ResponseUtil.write(response, new SysConfigWrapper(lstResult).wrap());
	}
	
	/**
	 * 跳转到页面
	 * @param sysDepartEntity
	 * @param model
	 * @return
	 */
	@RequestMapping("/add")
	public String add(SysConfigEntity sysConfigEntity, Model model) {
		if(StringUtils.isNotEmpty(sysConfigEntity.getId())) {
			SysConfigEntity config = sysConfigService.getById(sysConfigEntity.getId());
			model.addAttribute("config", config);
		}
		return "filesys/sysconfig/sysconfig.html";
	}
	
	/**
	 * 保存方法
	 * @param sysUserEntity
	 * @return
	 */
	@RequestMapping("/save")
	@RequiresPermissions("filesys/sysconfig/add")
	@ResponseBody
	@Log(type = LogType.save, name = "保存用户信息", memo = "新增或编辑保存了用户信息")
	public AjaxJson save(SysConfigEntity sysConfigEntity, String roleIds)  {
		AjaxJson j = new AjaxJson();
		
		try{
			//后端校验
			if(StringUtils.isEmpty(sysConfigEntity.getSysId())) {
				j.setSuccess(false);
				j.setMsg("系统编码不能为空");
				return j;
			}
			
			if(StringUtils.isEmpty(sysConfigEntity.getSysName())) {
				j.setSuccess(false);
				j.setMsg("系统名称不能为空");
				return j;
			}
			
			if(StringUtils.isEmpty(sysConfigEntity.getStatus())) {
				j.setSuccess(false);
				j.setMsg("状态不能为空");
				return j;
			}
			
			if(StringUtils.isEmpty(sysConfigEntity.getToken())) {
				j.setSuccess(false);
				j.setMsg("Token不能为空");
				return j;
			}
			
			//新增保存
			if(StringUtils.isEmpty(sysConfigEntity.getId())) {
				
				sysConfigService.saveUser(sysConfigEntity, roleIds);
			}
			//编辑保存
			else {
				SysConfigEntity tmp = sysConfigService.getById(sysConfigEntity.getId());
				MyBeanUtils.copyBeanNotNull2Bean(sysConfigEntity, tmp);
				sysConfigService.saveOrUpdateUser(tmp, roleIds);
			}
			
		}catch(Exception e) {
			log.error("保存用户信息报错，错误信息:" + e.getMessage());
			j.setSuccess(false);
			e.printStackTrace();
		}
		
		return j;
	}
	
	/**
	 *  删除操作
	 * @param sysUserEntity
	 * @return
	 */
	@RequestMapping("/delete")
	@RequiresPermissions("filesys:sysconfig:delete")
	@ResponseBody
	@Log(type = LogType.del, name = "删除用户信息", memo = "删除了用户信息")
	public AjaxJson delete(SysConfigEntity sysConfigEntity) {
		AjaxJson j = new AjaxJson();
		try {
			
			if(StringUtils.isNotEmpty(sysConfigEntity.getId())) {
				String userId = ShiroUtils.getSessionUserId();
				if(StringUtils.equals(userId, sysConfigEntity.getId())) {
					j.setSuccess(false);
					j.setMsg("不允许删除自身账户");
					return j;
				}
				SysConfigEntity item = sysConfigService.getById(sysConfigEntity.getId());
				if(null != item && "1".equals(item.getStatus())) {
					j.setSuccess(false);
					j.setMsg("不允许删除非禁用的数据");
					return j;
				}
				sysConfigService.delete(sysConfigEntity);
			}
			
		}catch(Exception e) {
			log.error("删除用户信息出错，错误信息:" + e.getMessage() );
			j.setSuccess(false);
			e.printStackTrace();
		}
		
		return j;
	}
	
	/**
	 * 公共弹出页面,  部门的选择
	 * @return
	 */
	@RequestMapping("/selectSys")
	public String selectDept(Model model) {
		QueryWrapper<SysConfigEntity> queryWrapper = new QueryWrapper<SysConfigEntity>();
		queryWrapper.eq("STATUS", "1");
		queryWrapper.orderByDesc("UPDATE_DATE");
		//顶级父级部门
		List<SysConfigEntity> lstParentDeparts = sysConfigService.list(queryWrapper);
		
		//拼接
		StringBuffer sb = new StringBuffer();
		sb = sb.append("[");
		departContact(lstParentDeparts, sb);
		sb = sb.append("]");
		
		//传值
		model.addAttribute("treeData", sb.toString());
		
		return "common/selectsys.html";
	}
	
	/**
	 * 采用递归的方式，拼接父子部门
	 * @param lstDeparts
	 * @param sb
	 */
	private void departContact(List<SysConfigEntity> lstDeparts, StringBuffer sb) {
		if(null != lstDeparts && lstDeparts.size() > 0) {
			for(int i = 0; i < lstDeparts.size(); i++) {
				SysConfigEntity depart = lstDeparts.get(i);
				//赋值树形结构
				sb = sb.append("{").append("text:").append("\"").append(depart.getSysId() + "-" + depart.getSysName()).append("\",").append("id:").append("\"").append(depart.getId()).append("\"");
				
				if(i == lstDeparts.size() - 1) {
					sb = sb.append("}");
				}else {
					sb = sb.append("},");
				}
			}
		}
	}
}
